#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib,"Ws2_32.lib")

int main()
{
    // 加载套接字库
    WORD wVersionRequested = MAKEWORD(1, 1);
    WSADATA wsaData;
    int err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
    {
        return -1;
    }
    if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
    {
        WSACleanup();
        return -1;
    }
    // 创建套接字
    SOCKET sockSrv = socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP);
    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_BROADCAST);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(6000);

    BOOL broadcast = TRUE;
    setsockopt(sockSrv,SOL_SOCKET,SO_BROADCAST, reinterpret_cast<char*>(&broadcast), sizeof(broadcast));

    int len = sizeof(SOCKADDR);
    int count{1};
    while (true)
    {
        const char* sendBuf = "UDP Broadcast";
        Sleep(1000);
        // 发送数据
        printf("Sending Count %d:\n", count++);
        sendto(sockSrv, sendBuf, strlen(sendBuf) + 1, 0, reinterpret_cast<SOCKADDR*>(&addrSrv), len);
    }
    closesocket(sockSrv);
    WSACleanup();
    return 0;
}
